package cn.wolfcode.web.advice;

import cn.wolfcode.exception.BusinessException;
import cn.wolfcode.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class ExceptionControllerAdvice {
    @ExceptionHandler(BusinessException.class)
    public void runtimeExceptionAdvice(BusinessException e,
                                       HandlerMethod handlerMethod,
                                       HttpServletResponse response) throws IOException {
        ResponseBody methodAnnotation = handlerMethod.getMethodAnnotation(ResponseBody.class);
        e.printStackTrace();
        if(methodAnnotation != null){
            JsonResult jsonResult = new JsonResult();
            jsonResult.setSuccess(false);
            jsonResult.setMsg(e.getMessage());
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(jsonResult));
            return;
        }
        response.sendRedirect("/error");
    }

    @ExceptionHandler(Exception.class)
    public void runtimeExceptionAdvice(Exception e,
                                       HandlerMethod handlerMethod,
                                       HttpServletResponse response) throws IOException {
        ResponseBody methodAnnotation = handlerMethod.getMethodAnnotation(ResponseBody.class);
        e.printStackTrace();
        if(methodAnnotation != null){
            JsonResult jsonResult = new JsonResult();
            jsonResult.setSuccess(false);
            jsonResult.setMsg("系统维护中,请稍后再试!");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(jsonResult));
            return;
        }
        response.sendRedirect("/error");
    }
}